package com.powerunion.datacollection.web.struts;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.powerunion.datacollection.config.ConfigUtil;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.service.ActivityManager;
import com.powerunion.datacollection.service.GlobalTargetsDataManager;
import com.powerunion.datacollection.service.MaintblDataManager;
import com.powerunion.datacollection.service.SubmissionWorkItemManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class GlobalTargetsDataAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			GlobalTargetsDataAction.class);
	private GlobalTargetsDataManager gtdm = null;

	public GlobalTargetsDataAction() {
		super();
		this.gtdm = new GlobalTargetsDataManager();
	}

	public void finalize() throws Throwable {
		this.gtdm = null;
		super.finalize();
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("text/json;charset=utf-8");
		String targetsData = request.getParameter("targetsData");
		String documentId = request.getParameter("documentId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		int iTemplate = Integer.parseInt(request.getParameter("iTemplate"));
		String actId = request.getParameter("actId");
		String mainTblFormValuesStr = request.getParameter("mainTblFormValuesStr");
		
		boolean flag = false;
		
		SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
		flag = swi.iSubWorkCommit(actId);
		if(flag){
			response.getWriter().write("{failure:true,data:'该任务已经结束！不能提交！'}");
			return null;
		}
		
		
		boolean mainFlag = false;

		Transaction maintblDatatransaction = null;
		try {
			maintblDatatransaction = TransactionHelper.getTransaction();
			maintblDatatransaction.begin();
			logger.debug("主表报送信息:" + mainTblFormValuesStr);
		
			//保存主表报送区数据
			if(!StringUtils.isEmpty(mainTblFormValuesStr)){
				MaintblDataManager mdm = new MaintblDataManager();
				MaintblData data = new MaintblData();
				data.setFormId(documentId);
				data.setActId(actId);
				data.setProcId(procId);
				data.setSubmiUser(submiUser);
				mainFlag = mdm.save(data, mainTblFormValuesStr);
			}else{
				mainFlag = true;
			}

			maintblDatatransaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				maintblDatatransaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				maintblDatatransaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		
		if(mainFlag){
			if(!StringUtils.isEmpty(targetsData)){
				Transaction transaction = null;
				try {
					transaction = TransactionHelper.getTransaction();
					transaction.begin();
					logger.debug("指标报送信息:" + targetsData);

					flag = this.gtdm.save(targetsData, documentId,submiUser,procId,iTemplate,actId); 

					transaction.commit();
				} catch (Exception e) {
					logger.error("", e);
					try {
						transaction.rollback();
					} catch (Exception e1) {
						logger.error("", e1);
						throw e;
					} finally {
						transaction = null;
						response.getWriter().write("{failure:true}");
					}
				}
				
				if (flag) {
					response.getWriter().write("{success:true}");
				} else {
					response.getWriter().write("{failure:true}");
				}
			}else{
				response.getWriter().write("{success:true}");
			}
		}else{
			response.getWriter().write("{failure:true}");
		}

		return null;
	}
	public ActionForward save4MaintblData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("text/json;charset=utf-8");
		String documentId = request.getParameter("documentId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");
		String mainTblFormValuesStr = request.getParameter("mainTblFormValuesStr");
		
		boolean flag = false;
		
		String adminName = ConfigUtil.getInstance().getParameter("system.manager.name");
		
		if(StringUtils.isEmpty(adminName)){
			throw new Exception("请配置系统管理员！");
		}
		
		if(!adminName.equals(submiUser)){//如果不是管理员身份则需要检查报送任务状态
			SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
			flag = swi.iSubWorkCommit(actId);
			if(flag){
				response.getWriter().write("{failure:true,data:'该任务已经结束！不能提交！'}");
				return null;
			}
		}
		

		boolean mainFlag = false;

		Transaction maintblDatatransaction = null;
		try {
			maintblDatatransaction = TransactionHelper.getTransaction();
			maintblDatatransaction.begin();
			logger.debug("主表报送信息:" + mainTblFormValuesStr);
		
			//保存主表报送区数据
			if(!StringUtils.isEmpty(mainTblFormValuesStr)){
				MaintblDataManager mdm = new MaintblDataManager();
				MaintblData data = new MaintblData();
				data.setFormId(documentId);
				data.setActId(actId);
				data.setProcId(procId);
				data.setSubmiUser(submiUser);
				mainFlag = mdm.save(data, mainTblFormValuesStr);
			}
			maintblDatatransaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				maintblDatatransaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				maintblDatatransaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		if(mainFlag){
			response.getWriter().write("{success:true}");
		}else{
			response.getWriter().write("{failure:true}");
		}

		return null;
	}
	/**
	 * 保存初始化表单数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward initDataForm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String targetsData = request.getParameter("targetsData");
		String documentId = request.getParameter("documentId");
		int permissionUPFile =  request.getParameter("permissionUPFile")==null?0:Integer.parseInt(request.getParameter("permissionUPFile"));
		//String mainTblFormValuesStr = request.getParameter("mainTblFormValuesStr");
		
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("初始化表单指标报送数据:" + targetsData);
			//logger.debug("初始化表单附件数据:" + accessoriesData);
			//logger.debug("初始化表单主表报送数据:" + mainTblFormValuesStr);

			//保存指标报送区数据
			boolean targetflag = this.gtdm.save(targetsData, documentId,permissionUPFile);
	
			if (targetflag) {
				response.getWriter().write("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}
	
	public ActionForward getTemplateTargetInitData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String documentId = request.getParameter("formId");

		List array = this.gtdm.getTemplateData(documentId);
		
		JSONArray ja =  JSONArray.fromObject(array);
		String result = "{results:"+ja+"}";
		logger.debug("getTemplateTargetInitData:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	/**
	 * 获取某个上报的指标信息数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getTargetSubmiData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String documentId =  request.getParameter("formId");	
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");	
		List array = this.gtdm.getTargetSubmiData(documentId, submiUser, procId, actId);
		
		JSONArray ja =  JSONArray.fromObject(array);
		String result = "{results:"+ja+"}";
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	/**
	 * 获取某个采集步骤的上报的所有数据
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getActSubmiData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String documentId =  request.getParameter("formId");	
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");	
		
		List array = this.gtdm.getApproveActivityData(documentId, procId, actId);
		
		JSONArray ja =  JSONArray.fromObject(array);
		String result = "{results:"+ja+"}";
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	public ActionForward getNextActivity(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActivityManager am = new ActivityManager();
		String actId = request.getParameter("actId");
		String result = "";
		result = am.getNextActivity(actId);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
}
